package com.example.demo.service.homepage.impl;

import com.alibaba.fastjson.JSON;
import com.example.demo.entity.CollectionName;
import com.example.demo.entity.base.Condition;
import com.example.demo.service.comm.AggregationUtil;
import com.example.demo.service.comm.MongodbService;
import com.example.demo.service.homepage.HomePageService;
import com.example.demo.utils.DateUtil;
import com.example.demo.utils.StringUtil;
import com.example.demo.utils.rich.TextUtil;
import org.bson.Document;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.*;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.CriteriaDefinition;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * @description:
 * @author: cj
 * @create: 10-12-23 10:58:07
 */
@Service("HomePageService")
public class HomePageServiceImpl implements HomePageService {

    @Resource
    MongoTemplate mongoTemplate;

    @Resource
    MongodbService mongodbService;

    /**
     * 获取首页数据 （根据条件）
     *
     * @param map 条件
     * @return 数据
     */
    @Override
    public List<Map> findHomePageData(Map<String, Object> map) {
        if (map == null || map.isEmpty()) {
            throw new RuntimeException( "参数错误" );
        } else {
            Criteria criteria = new Criteria();
            if (StringUtil.isEmpty( map.get( "userId" ) )) {
                String id = map.get( "userId" ).toString();
                criteria = criteria.andOperator( Criteria.where( "user_id" ).is( id ) );
            }
            List<Map> mapList = mongoTemplate.find( Query.query( criteria ), Map.class, CollectionName.USER_IMG );
            for (Map next : mapList) {
                next.put( "_id", next.get( "_id" ).toString() );
            }
            return mapList;
        }
    }

    /**
     * 获取首页的文章
     *
     * @param page     分页参数
     * @param pageSize 分页参数
     * @return 文章
     */
    @Override
    public List<Map> findBbs(Integer page, Integer pageSize) {
        MatchOperation match = Aggregation.match( Criteria.where( "state" ).is( "1" ) );
        SortOperation sort = Aggregation.sort( Sort.by( Sort.Order.desc( "sort" ) ) );
        SkipOperation skip = Aggregation.skip( Long.valueOf( (page - 1) * pageSize ) );
        LimitOperation limit = Aggregation.limit( Long.valueOf( pageSize ) );
        AggregationOperation toStr = var -> new Document( "$addFields", new Document( "_id", new Document( "$toString", "$_id" ) ) );
        ProjectionOperation projectionOperation = Aggregation.project().andExclude( "content" );
        Aggregation aggregation = Aggregation.newAggregation( match,projectionOperation, skip, limit, sort, toStr );
        AggregationResults<Map> aggregate = mongoTemplate.aggregate( aggregation, CollectionName.ESSAY, Map.class );
        List<Map> mappedResults = aggregate.getMappedResults();
        if (!CollectionUtils.isEmpty( mappedResults )) {
            return mappedResults;
        }
        return null;
    }

    /**
     * 添加文章
     *
     * @param map 文章信息（title 标题，content 内容，cover 封面，author 作者, time 时间，intro 简介
     *            ——,comment_sum 评论数量，give_like_sum 点赞数量，read_sum 阅读量,state 状态）
     */
    @Override
    public Map<String, Object> addBbs(Map<String, Object> map) {
        if (StringUtil.isEmpty( map.get( "title" ) ) ||
                StringUtil.isEmpty( map.get( "content" ) ) ||
                StringUtil.isEmpty( map.get( "author" ) )) {
            throw new RuntimeException( "参数错误" );
        }
        map.put( "comment_sum", 0 );
        map.put( "give_like_sum", 0 );
        map.put( "read_sum", 0 );
        map.put( "state", "1" );
        map.put( "time", DateUtil.dateToString( new Date() ) );
        String content = map.get( "content" ).toString();
        if (map.get( "intro" ) == null) {
            String text = TextUtil.getText( content );
            String substring = text.substring( 0, 200 );
            map.put( "intro", substring );
        }
        Map<String, Object> insert = mongoTemplate.insert( map, CollectionName.ESSAY );
        insert.put( "_id", insert.get( "_id" ).toString() );
        return insert;
    }

    /**
     * 获取首页信息
     *
     * @param condition 条件操作对象
     * @return 首页信息
     */
    @Override
    public Map<String, Object> findHome(Condition condition) {
        CriteriaDefinition criteriaDefinition = Condition.changeCriteria( condition );
        MatchOperation match = Aggregation.match( criteriaDefinition );
        UnwindOperation unwind = Aggregation.unwind( "loginUsers", true );
        AggregationOperation addFieldsToId = AggregationUtil.addFieldsToId( "loginUsers" );
        AggregationOperation addFieldsToStr = AggregationUtil.addFieldsToStr( "_id");
        LookupOperation lookup = Aggregation.lookup( CollectionName.USER, "loginUsers", "_id", "user" );
        LookupOperation showLookup = Aggregation.lookup( CollectionName.ESSAY, "_id", "show", "shows" );

        AggregationOperation aggregationOperation = AggregationUtil.addFieldsToStr( "user._id" );
        UnwindOperation userUnwind = Aggregation.unwind( "user", true );
        String groupStr = "  {\n" +
                "    $group: {\n" +
                "        _id: '$_id',\n" +
                "        loginUsers: {\n" +
                "            $push: '$user'\n" +
                "        },\n" +
                "        'state': {\n" +
                "            '$first': '$state'\n" +
                "        },\n" +
                "        'cover': {\n" +
                "            '$first': '$cover'\n" +
                "        },\n" +
                "        'shows': {\n" +
                "            '$first': '$shows'\n" +
                "        },\n" +
                "        'webBrief': {\n" +
                "            '$first': '$webBrief'\n" +
                "        }\n" +
                "    }\n" +
                "}\n";
        AggregationOperation group = var -> new Document( JSON.parseObject( groupStr ) );
        Aggregation aggregation = Aggregation.newAggregation( match, unwind, addFieldsToId,addFieldsToStr, lookup, showLookup, userUnwind, aggregationOperation, group );
        AggregationResults<Map> aggregate = mongoTemplate.aggregate( aggregation, CollectionName.HOMEPAGE, Map.class );
        List<Map> mapList = aggregate.getMappedResults();
        Iterator<Map> iterator = mapList.iterator();
        while (iterator.hasNext()) {
            Map next = iterator.next();
            next.put( "_id", next.get( "_id" ).toString() );
            List<Map<String, Object>> shows = (List<Map<String, Object>>) next.get( "shows" );
            shows.forEach( item->{item.put( "_id",item.get( "_id" ).toString() );} );
        }
        if (CollectionUtils.isEmpty( mapList )) {
            return null;
        }
        return mapList.get( 0 );
    }

//    public static void main(String[] args) {
//        BasicTextEncryptor textEncryptor = new BasicTextEncryptor();
//        //加密所需的salt(盐)
//        textEncryptor.setPassword( "example" );
//        //要加密的数据（数据库的用户名或密码）
//        String username = textEncryptor.encrypt( "chenjie" );
//        String password = textEncryptor.encrypt( "chenjie" );
//        System.out.println( "username:" + username );
//        System.out.println( "password:" + password );
//        String decrypt = textEncryptor.decrypt( password );
//        System.out.println(decrypt);
//    }
}
